package net.oschina.app.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import net.oschina.app.R;
import net.oschina.app.bean.Tweet;
import net.oschina.app.bean.TweetsList;
import net.oschina.app.bean.User;
import net.oschina.app.emoji.InputHelper;
import net.oschina.app.ui.view.CircleImageView;
import net.oschina.app.ui.widget.MyLinkMovementMethod;
import net.oschina.app.ui.widget.MyURLSpan;
import net.oschina.app.ui.widget.TweetTextView;
import net.oschina.app.util.KJAnimations;
import net.oschina.app.util.StringUtils;
import net.oschina.app.util.TypefaceUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static net.oschina.app.MApp.mContext;

/**
 * Created by CXB on 2017/4/1.
 */

public class TweetNewsAdapter extends BaseRecyclerViewAdapter {

    private TweetsList tweetsList;
    private List<Tweet> mTweets = new ArrayList<>();

    public TweetNewsAdapter(Context context, TweetsList tweetsList) {
        super(context);
        mTweets = tweetsList.getTweetslist();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.list_cell_tweet, parent, false);
        MyHolder myHolder = new MyHolder(view);
        return myHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
        MyHolder myHolder = (MyHolder) holder;
        refreshHolderView(mTweets.get(position), myHolder);
    }


    @Override
    public int getItemCount() {
        return mTweets.size();
    }

    @OnClick({R.id.iv_tweet_image, R.id.tv_like_state})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_tweet_image:
                break;
            case R.id.tv_like_state:
                break;
        }
    }


    class MyHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.iv_tweet_face)
        CircleImageView mIvTweetFace;
        @BindView(R.id.tv_tweet_name)
        TextView mTvTweetName;
        @BindView(R.id.tweet_item)
        TweetTextView mTweetItem;
        @BindView(R.id.iv_tweet_image)
        ImageView mIvTweetImage;
        @BindView(R.id.tv_likeusers)
        TextView mTvLikeusers;
        @BindView(R.id.tv_tweet_time)
        TextView mTvTweetTime;
        @BindView(R.id.tv_tweet_platform)
        TextView mTvTweetPlatform;
        @BindView(R.id.tv_del)
        TextView mTvDel;
        @BindView(R.id.tv_like_state)
        TextView mTvLikeState;
        @BindView(R.id.tv_tweet_comment_count)
        TextView mTvTweetCommentCount;
        @BindView(R.id.ll_info)
        RelativeLayout mLlInfo;

        public MyHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public void refreshHolderView(final Tweet tweet, final MyHolder holder) {
        //设置头像
        Glide.with(mContext).load(tweet.getPortrait()).into(holder.mIvTweetFace);
        //设置内容图片
        Glide.with(mContext).load(tweet.getImgBig()).fitCenter().into(holder.mIvTweetImage);
        holder.mTvDel.setVisibility(View.GONE);
        holder.mTvTweetName.setText(tweet.getAuthor());//作者
        holder.mTvTweetTime.setText(StringUtils.friendly_time(tweet.getPubDate()));
        //内容
        holder.mTweetItem.setMovementMethod(MyLinkMovementMethod.a());
        holder.mTweetItem.setFocusable(false);
        holder.mTweetItem.setLongClickable(false);

        Spanned span = Html.fromHtml(tweet.getBody().trim());

        if (!StringUtils.isEmpty(tweet.getAttach())) {

            SpannableString str = new SpannableString("c");
            holder.mTweetItem.setText(str);
            span = InputHelper.displayEmoji(mContext.getResources(), span);
            holder.mTweetItem.append(span);
        } else {
            span = InputHelper.displayEmoji(mContext.getResources(), span);
            holder.mTweetItem.setText(span);
        }
        MyURLSpan.parseLinkText(holder.mTweetItem, span);

        //评论条数
        holder.mTvTweetCommentCount.setText(tweet.getCommentCount() + "");
        if (tweet.getLikeUser() == null) {
            holder.mTvLikeusers.setVisibility(View.GONE);
        }
        //设置点赞效果
        setLikeUsers(tweet, mContext, holder.mTvLikeusers, true);

        //设置点赞的字体图标
        TypefaceUtils.setTypeface(mContext, holder.mTvLikeState);

        if (tweet.getLikeUser() == null) {
            holder.mTvLikeState.setVisibility(View.GONE);
        } else {
            holder.mTvLikeState.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateLikeState(tweet, holder);
                }
            });
        }

        if (tweet.getIsLike() == 1) {
            holder.mTvLikeState.setTextColor(mContext.getResources().getColor(R.color.day_colorPrimary));
        } else {
            holder.mTvLikeState.setTextColor(mContext.getResources().getColor(R.color.gray));
        }

    }


    private void updateLikeState(Tweet tweet, MyHolder holder) {
        User user = new User();
        user.setName("billy");
        user.setId(10001);

        if (tweet.getIsLike() == 1) {
            tweet.setIsLike(0);
            tweet.setLikeCount(tweet.getLikeCount() - 1);
            if (!tweet.getLikeUser().isEmpty()) {
                tweet.getLikeUser().remove(0);
            }
            holder.mTvLikeState.setTextColor(mContext.getResources().getColor(R.color
                    .gray));
        } else {
            holder.mTvLikeState.setAnimation(KJAnimations.getScaleAnimation(1.5f, 300));
            holder.mTvLikeState.setTextColor(mContext.getResources().getColor(R.color
                    .day_colorPrimary));
            tweet.setIsLike(1);
            tweet.setLikeCount(tweet.getLikeCount() + 1);
            tweet.getLikeUser().add(0, user);
        }
        setLikeUsers(tweet, mContext, holder.mTvLikeusers, true);
    }

    /**
     * 处理点赞
     *
     * @param tweet
     * @param context
     * @param tvLikeusers
     * @param limit
     */
    private void setLikeUsers(Tweet tweet, Context context, TextView tvLikeusers, boolean limit) {
        // 构造多个超链接的html, 通过选中的位置来获取用户名
        if (tweet.getLikeCount() > 0 && tweet.getLikeUser() != null && !tweet.getLikeUser().isEmpty()) {
            tvLikeusers.setVisibility(View.VISIBLE);
            tvLikeusers.setMovementMethod(LinkMovementMethod.getInstance());
            tvLikeusers.setFocusable(false);
            tvLikeusers.setLongClickable(false);
            tvLikeusers.setText(addClickablePart(tweet, context, limit), TextView.BufferType.SPANNABLE);
        } else {
            tvLikeusers.setVisibility(View.GONE);
            tvLikeusers.setText("");
        }
    }

    /**
     * @return
     */
    private SpannableStringBuilder addClickablePart(Tweet tweet, final Context context, boolean limit) {

        StringBuilder sbBuilder = new StringBuilder();
        int showCunt = tweet.getLikeUser().size();
        if (limit && showCunt > 4) {//最多显示4个
            showCunt = 4;
        }

        for (int i = 0; i < showCunt; i++) {
            sbBuilder.append(tweet.getLikeUser().get(i).getName() + "、");
        }

        String likeUsersStr = sbBuilder.substring(0, sbBuilder.lastIndexOf("、")).toString();

        SpannableString spanStr = new SpannableString("");
        SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
        ssb.append(likeUsersStr);

        String[] likeUsers = likeUsersStr.split("、");

        if (likeUsers.length > 0) {
            // 最后一个
            for (int i = 0; i < likeUsers.length; i++) {
                final String name = likeUsers[i];
                final int start = likeUsersStr.indexOf(name) + spanStr.length();
                final int index = i;
                ssb.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        // ds.setColor(R.color.link_color); // 设置文本颜色
                        // 去掉下划线
                        ds.setUnderlineText(false);
                    }

                }, start, start + name.length(), 0);
            }
        }
        if (likeUsers.length < tweet.getLikeCount()) {
            ssb.append("等");
            int start = ssb.length();
            String more = tweet.getLikeCount() + "人";
            ssb.append(more);
            ssb.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    // ds.setColor(R.color.link_color); // 设置文本颜色
                    // 去掉下划线
                    ds.setUnderlineText(false);
                }

            }, start, start + more.length(), 0);
            return ssb.append("觉得很赞");
        } else {
            return ssb.append("觉得很赞");
        }
    }
}
